package com.qpl.depression.cms.service.impl;


import com.qpl.depression.cms.common.Const;
import com.qpl.depression.cms.common.ServerResponse;
import com.qpl.depression.cms.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;


/**
 * @Author
 * @Date 2020/2/8 23:00
 * @Desc
 **/
@Service
public class FileServiceImpl implements FileService {

    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    @Override
    public ServerResponse upload(MultipartFile file) {
        // 获取原始文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 重新命名
        fileName = UUID.randomUUID().toString().replace("-", "") + suffixName;
        // 文件上传目录
        File targetFile = new File(Const.FILE_PATH);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        logger.info("******开始上传文件******");
        File saveFile = new File(targetFile, fileName);
        try {
            file.transferTo(saveFile);
            logger.info("******文件上传成功******");
            return ServerResponse.createBySuccess("上传成功",  fileName);
        } catch (IOException e) {
            logger.error("******文件上传失败******", e);
        }
        return ServerResponse.createByErrorMessage("上传失败");
    }


    @Override
    public HashMap uploads(MultipartFile file) {
        HashMap hashMap = new HashMap();
        // 获取原始文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 重新命名
        fileName = UUID.randomUUID().toString().replace("-", "") + suffixName;
        // 文件上传目录
        File targetFile = new File(Const.FILE_PATH);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        logger.info("******开始上传文件******");
        File saveFile = new File(targetFile, fileName);
        try {
            file.transferTo(saveFile);
            logger.info("******文件上传成功******");
            hashMap.put("code", 0);
            hashMap.put("msg", "上传成功！");
            HashMap map = new HashMap();
            map.put("src", "/" + fileName);
            map.put("title", "图片");
            hashMap.put("data", map);
            return hashMap;
        } catch (IOException e) {
            logger.error("******文件上传失败******", e);
        }
        hashMap.put("code", 500);
        hashMap.put("msg", "上传失败！");
        HashMap map = new HashMap();
        map.put("src", "");
        map.put("title", "图片");
        hashMap.put("data", map);
        return hashMap;
    }


}
